<?php
/**
 * Created by PhpStorm.
 * User: huizhou
 * Date: 2017/10/31
 * Time: 10:44
 */

include_once( dirname(__FILE__).'/../../library/exception' );


class ExceptionHandler  extends Yaf_Controller_Abstract
{
        private $code;
        private $msg;
        private $errorCode;
        private $status;
        //需要返回客户端当前请求的URL路径
    /**
     * 所有代码抛出异常都会通过这个render方法来渲染，来决定最后返回到客户端是什么形式的错误
     * @param \Exception $e
     * @return \think\Response|\think\response\Json
     */
        public function render(\Exception $e) {
            if($e instanceof BaseException) {
                // 如果是自定义的异常
                $this->code = $e->code;
                $this->msg = $e ->msg;
                $this->errorCode = $e->errorCode;
                $this->status = $e->status;
            }else {
                $this->code = 500;
                $this->msg = '服务器错误';
                $this->errorCode = 999;
                $this->status = 0 ;
                $this->recordErrorLog($e);
            }
            $request = $this->getRequest();

            $result = [

                'status' => $this->status,
                'msg'=> $this->msg,
                'error_code'=>$this->errorCode,
                'request_url'=> $request->getRequestUri()
            ];
            return json($result,$this->code);
        }

        /**
         * 记录日志
         * @param Exception $e
         */
        private function recordErrorLog(\Exception $e){
            // 记录日志，设置日志级别
           $this->record($e->getMessage(),'error');
        }


        /**
         * 记录调试信息
         * @param mixed  $msg  调试信息
         * @param string $type 信息类型
         * @return void
         */
        public function record($msg, $type = 'log')
        {
            $log = array();
            $log[$type][] = $msg;
                // 命令行下面日志写入改进
            $this->save_log($log);
        }

        /**
         * 存储log
         * @param $data
         */
        function save_log($data){
            $log_file = dirname(__FILE__).'/../../log/'.date('Ymd',time()).'_all.log';
            $content =var_export($data,TRUE);
            $content .= "\r\n\n";
            file_put_contents($log_file,$content, FILE_APPEND);
        }
}
